import os
import queue
import logging
from threading import Thread
from pyftpdlib.servers import FTPServer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.authorizers import DummyAuthorizer


class SimpleFTPServer:
    def __init__(self, root_dir, port=21, user="user", password="12345"):
        self.root_dir = root_dir
        self.port = port
        self.user = user
        self.password = password
        self._server = None
        self._ftp_thread = None
        self._worker_thread = None
        self._image_queue = queue.Queue()
        self.on_image_received = None  # 回调 func(cam_id, img_bytes)
        self.ip_cam_map = {}  # {客户端IP: cam_id}
        self._running = True

    def set_ip_cam_map(self, mapping: dict):
        self.ip_cam_map = mapping

    def _image_worker(self):
        while self._running:
            try:
                cam_id, file_path = self._image_queue.get(timeout=1)
                with open(file_path, "rb") as f:
                    img_data = f.read()
                file_size_kb = len(img_data) / 1024

                logging.info(f"[FTP] 处理图像: {file_path} 映射为 {cam_id}，大小: {file_size_kb:.1f} KB")
                if self.on_image_received:
                    self.on_image_received(cam_id, img_data)

                os.remove(file_path)
                logging.info(f"[FTP] 已删除图像文件: {file_path}")

            except queue.Empty:
                continue
            except Exception as e:
                logging.error(f"[FTP] 图像处理失败: {e}")

    def start(self):
        if not os.path.exists(self.root_dir):
            os.makedirs(self.root_dir)

        authorizer = DummyAuthorizer()
        authorizer.add_user(self.user, self.password, self.root_dir, perm="elradfmwMT")
        authorizer.add_anonymous(self.root_dir, perm="elradfmwMT")

        parent = self

        class Handler(FTPHandler):
            def on_file_received(handler_self, file_path):
                client_ip = handler_self.remote_ip
                cam_id = parent.ip_cam_map.get(client_ip, "unknown")

                logging.info(f"[FTP] 接收到文件: {file_path} 来自IP: {client_ip} 映射摄像头: {cam_id}")
                parent._image_queue.put((cam_id, file_path))

        handler = Handler
        handler.authorizer = authorizer
        self._server = FTPServer(("0.0.0.0", self.port), handler)

        # 启动 FTP 线程
        self._ftp_thread = Thread(target=self._server.serve_forever, daemon=True)
        self._ftp_thread.start()
        logging.info(f"[FTP] 服务器启动，监听端口 {self.port}，根目录 {self.root_dir}")

        # 启动图像处理线程
        self._worker_thread = Thread(target=self._image_worker, daemon=True)
        self._worker_thread.start()

    def stop(self):
        self._running = False
        if self._server:
            logging.info("[FTP] 正在关闭服务器...")
            self._server.close_all()
        if self._ftp_thread:
            self._ftp_thread.join(timeout=2)
        if self._worker_thread:
            self._worker_thread.join(timeout=2)
        logging.info("[FTP] 服务器已停止")
